// import 'dart:convert';
// import 'package:http/http.dart' as http;
// import 'package:flutter/material.dart';
// import 'PetsDetail.dart';
// import 'pet.dart';
//
// class SmallWorldPage extends StatefulWidget {
//   const SmallWorldPage({super.key});
//
//   @override
//   _SmallWorldPageState createState() => _SmallWorldPageState();
// }
//
// class _SmallWorldPageState extends State<SmallWorldPage> {
//   List<Pet> _pets = [];
//   bool _isLoading = true;
//   bool _hasError = false;
//
//
//   @override
//   void initState() {
//     super.initState();
//     _fetchData();
//   }
//
//   Future<void> _fetchData() async {
//     setState(() {
//       _isLoading = true;
//       _hasError = false;
//     });
//     try {
//       final pets = await getPets();
//       setState(() {
//         _pets = pets;
//         _isLoading = false;
//       });
//     } catch (e) {
//       setState(() {
//         _hasError = true;
//         _isLoading = false;
//       });
//       print('Error fetching data: $e');
//     }
//   }
//
//   Future<void> _refreshData() async {
//     await _fetchData();
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       // appBar: AppBar(
//       //   title: const Text("小世界"),
//       // ),
//       body: _isLoading
//           ? const Center(child: CircularProgressIndicator())
//           : _hasError
//           ? Center(
//         child: Column(
//           mainAxisAlignment: MainAxisAlignment.center,
//           children: [
//             const Text('数据加载失败，请稍后重试！', style: TextStyle(color: Colors.red)),
//             ElevatedButton(
//               onPressed: _fetchData,
//               child: const Text('重试'),
//             ),
//           ],
//         ),
//       )
//           : RefreshIndicator(
//         onRefresh: _refreshData,
//         child: ListView.builder(
//           itemCount: _pets.length,
//           itemBuilder: (context, index) {
//             final pet = _pets[index];
//             return Card(
//               color: Colors.grey[200],
//               elevation: 5.0,
//               margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
//               child: InkWell(
//                 onTap: () {
//                   Navigator.push(
//                     context,
//                     MaterialPageRoute(
//                       builder: (context) => PetsDetailPage(pet: pet, friends: friendsList),
//                     ),
//                   );
//                 },
//                 child: Column(
//                   crossAxisAlignment: CrossAxisAlignment.start,
//                   children: [
//                     pet.coverURL.isNotEmpty
//                         ? Image.network(
//                       pet.coverURL,
//                       fit: BoxFit.cover,
//                       errorBuilder: (context, error, stackTrace) {
//                         return const Icon(
//                           Icons.broken_image,
//                           size: 80,
//                           color: Colors.grey,
//                         );
//                       },
//                     )
//                         : const Icon(Icons.broken_image, size: 80, color: Colors.grey),
//                     Padding(
//                       padding: const EdgeInsets.all(10.0),
//                       child: Text(
//                         '${pet.name} (${pet.engName})',
//                         style: const TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
//                       ),
//                     ),
//                     Padding(
//                       padding: const EdgeInsets.symmetric(horizontal: 10.0),
//                       child: Text(
//                         pet.desc,
//                         style: const TextStyle(fontSize: 14.0, color: Colors.black54),
//                         maxLines: 3,
//                         overflow: TextOverflow.ellipsis,
//                       ),
//                     ),
//                     Padding(
//                       padding: const EdgeInsets.all(10.0),
//                       child: Text(
//                         '原产地: ${pet.nation} | 寿命: ${pet.life}',
//                         style: const TextStyle(fontSize: 12.0, color: Colors.black54),
//                       ),
//                     ),
//                   ],
//                 ),
//               ),
//             );
//           },
//         ),
//       ),
//     );
//   }
//
//   Future<List<Pet>> getPets() async {
//     final response = await http.get(Uri.parse(
//         'https://apis.tianapi.com/pet/index?key=9acd0db09070970c72540770f62fffce&num=10&page=1'));
//
//     if (response.statusCode == 200) {
//       Utf8Decoder decoder = const Utf8Decoder();
//       Map<String, dynamic> result =
//       jsonDecode(decoder.convert(response.bodyBytes));
//
//       if (result['code'] == 200) {
//         List<dynamic> petList = result['result']['list'];
//         return petList.map((item) => Pet.fromJson(item)).toList();
//       } else {
//         throw Exception('Failed to load pets: ${result['msg']}');
//       }
//     } else {
//       throw Exception(
//           'Failed to load pets with status code: ${response.statusCode}');
//     }
//   }
// }

import 'dart:convert';
import 'dart:math';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'PetsDetail.dart'; // 确保导入正确的 PetsDetailPage
import 'Pet.dart'; // 确保使用正确的 Pet 类

class SmallWorldPage extends StatefulWidget {
  const SmallWorldPage({super.key});

  @override
  _SmallWorldPageState createState() => _SmallWorldPageState();
}

class _SmallWorldPageState extends State<SmallWorldPage> {
  List<Pet> _pets = [];
  bool _isLoading = true;
  bool _hasError = false;

  List<Map<String, String>> friendsList = [
    {
      'name': '炎龙铠甲',
      'avatar': 'images/1.jpg',
      'messages': '我要向你分享我的宠物信息'  // 初始消息列表为空
    },
    {
      'name': '黑犀铠甲',
      'avatar': 'images/2.jpg',
      'messages': '我要向你分享我的宠物信息'
    },
    {
      'name': '烈焰星神',
      'avatar': 'images/3.jpg',
      'messages': '我要向你分享我的宠物信息'
    },
    {
      'name': '盖亚',
      'avatar': 'images/4.jpg',
      'messages': '我要向你分享我的宠物信息'
    },
    {
      'name': '宙斯',
      'avatar': 'images/5.jpg',
      'messages': '我要向你分享我的宠物信息'
    },
    {
      'name': '阿波罗',
      'avatar': 'images/6.jpg',
      'messages': '我要向你分享我的宠物信息'
    },
    {
      'name': '维纳斯',
      'avatar': 'images/7.jpg',
      'messages': '我要向你分享我的宠物信息'
    },
    {
      'name': '萨隆',
      'avatar': 'images/8.jpg',
      'messages': '我要向你分享我的宠物信息'
    },
    {
      'name': '普罗托',
      'avatar': 'images/9.jpg',
      'messages': '我要向你分享我的宠物信息'
    },
    {
      'name': '波塞冬',
      'avatar': 'images/10.jpg',
      'messages': '我要向你分享我的宠物信息'
    },
    {
      'name': '卡洛斯',
      'avatar': 'images/11.jpg',
      'messages': '我要向你分享我的宠物信息'
    },
    {
      'name': '阿瑞斯',
      'avatar': 'images/12.jpg',
      'messages': '我要向你分享我的宠物信息'
    },
    // 根据需要添加更多朋友
  ];

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  Future<void> _fetchData() async {
    setState(() {
      _isLoading = true;
      _hasError = false;
    });
    try {
      final pets = await getPets();
      setState(() {
        _pets = pets;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _hasError = true;
        _isLoading = false;
      });
      print('Error fetching data: $e');
    }
  }

  Future<void> _refreshData() async {
    await _fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _hasError
          ? Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('数据加载失败，请稍后重试！', style: TextStyle(color: Colors.red)),
            ElevatedButton(
              onPressed: _fetchData,
              child: const Text('重试'),
            ),
          ],
        ),
      )
          : RefreshIndicator(
        onRefresh: _refreshData,
        child: ListView.builder(
          itemCount: _pets.length,
          itemBuilder: (context, index) {
            final pet = _pets[index];
            return Card(
              color: Colors.grey[200],
              elevation: 5.0,
              margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
              child: InkWell(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => PetsDetailPage(
                        pet: pet,
                        friends: friendsList, // 传递朋友列表
                      ),
                    ),
                  );
                },
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    pet.coverURL.isNotEmpty
                        ? Image.network(
                      pet.coverURL,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) {
                        return const Icon(
                          Icons.broken_image,
                          size: 80,
                          color: Colors.grey,
                        );
                      },
                    )
                        : const Icon(Icons.broken_image, size: 80, color: Colors.grey),
                    Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Text(
                        '${pet.name} (${pet.engName})',
                        style: const TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10.0),
                      child: Text(
                        pet.desc,
                        style: const TextStyle(fontSize: 14.0, color: Colors.black54),
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Text(
                        '原产地: ${pet.nation} | 寿命: ${pet.life}',
                        style: const TextStyle(fontSize: 12.0, color: Colors.black54),
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  Future<List<Pet>> getPets() async {
    // 创建一个随机数生成器
    final random = Random();

    // 随机生成 num 和 page 参数，范围是 10-20
    int num = random.nextInt(6) + 10;  // 生成一个 [10, 15] 范围内的随机数
    int page = random.nextInt(11) + 1; // 同样为 page 生成一个 [1, 11] 范围内的随机数

    final response = await http.get(Uri.parse(
        'https://apis.tianapi.com/pet/index?key=9acd0db09070970c72540770f62fffce&num=$num&page=$page'));

    if (response.statusCode == 200) {
      Utf8Decoder decoder = const Utf8Decoder();
      Map<String, dynamic> result =
      jsonDecode(decoder.convert(response.bodyBytes));

      if (result['code'] == 200) {
        List<dynamic> petList = result['result']['list'];
        return petList.map((item) => Pet.fromJson(item)).toList();
      } else {
        throw Exception('Failed to load pets: ${result['msg']}');
      }
    } else {
      throw Exception(
          'Failed to load pets with status code: ${response.statusCode}');
    }
  }
}
